package scau.edu.cn.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @description:
 * @author: yuxiang
 * @create: 2020-08-15 11:14
 **/
@RestController
@RequestMapping("/photo")
public class PhotoController {


    @Value("${web.upload-path}")
    private String localPath;

//    @ResponseStatus(code=HttpStatus.NOT_FOUND,reason="not exists image")
    @GetMapping("/getImg/{type}/{id}")
    public void getImg(@PathVariable String id, @PathVariable String type,HttpServletResponse response) throws IOException {

//        ApiResponse apiResponse = new ApiResponse();
        System.out.println("照片id======>>>"+id);
//        System.out.println(ResourceUtils.CLASSPATH_URL_PREFIX+"images/"+id+".jpg");
        try {
//            ClassPathResource classPathResource = new ClassPathResource("images/"+id+".jpg");
//            FileInputStream fis = (FileInputStream) classPathResource.getInputStream();
            //图片实际路径
            String realPath = localPath+"/"+type+"/"+id;
            //获取图片
            File file = new File(realPath);
//            File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"images/"+id+".jpg");
            if (!file.exists()){
                response.sendError(404,"图片不存在");
                System.out.println("图片不存在");
            }else {
                response.setContentLength((int)file.length());
                FileInputStream fis = new FileInputStream(file);
                OutputStream os = response.getOutputStream();

                byte[] buf = new byte[1024 * 256];
                int i;
                while ((i = fis.read(buf)) != -1) {
                    os.write(buf, 0, i);
                }
                os.flush();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
